package com.google.denta.utils;

import java.util.HashSet;
import java.util.Set;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.google.denta.entity.User;
import com.google.denta.service.UserService;

public class SecurityPolicy {
    private Set<String> granted = null;

    public SecurityPolicy() {
        granted = new HashSet<String>();
        Set<GrantedAuthority> grantedRoles =
                new HashSet<GrantedAuthority>(getDatails().getAuthorities());
        for (GrantedAuthority grant : grantedRoles) {
            granted.add(grant.getAuthority());
        }
    }

    public boolean ifAnyGranted(String[] roles) {
        for (String role : roles) {
            if (granted.contains(role)) {
                return true;
            }
        }
        return false;
    }

    public boolean ifIsGranted(String role) {
        if (granted.contains(role)) {
            return true;
        }
        return false;
    }

    public boolean ifNotGranted(String role) {
        return !ifIsGranted(role);
    }

    public static User userObject(UserService service) {
        return service.getUserByName(getDatails().getUsername());
    }


    private static UserDetails getDatails() {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication auth = context.getAuthentication();
        return (UserDetails) auth.getPrincipal();
    }
    
    public String toString() {
        String result = "";
        for (String grant : granted) {
            result += grant+";";
        }
        return result;
    }
} // class
